package constant.milk.cashbook.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.database.DbAdapter;
import constant.milk.cashbook.database.DbDeleteQuery;
import constant.milk.cashbook.database.DbSetting;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.MilkUtil;

public class DataMainActivity extends SuperActivity
{
	public static final String dirName = "HouseCashBook";
	public static final String dirNameAuto = "HouseCashBook/Auto";
	public static final String dirNameExcel = "HouseCashBook/Excel";
	public static final String dirNameEmail = "HouseCashBook/Email";
	public static final String dirNamePhoto = "HouseCashBook/Photo";
	
	public static final String EMAIL_FILE_NAME = "HouseCashBookEMAIL";
	
	private View backupView;
	private View rollbankView;
	private View resetView;
	private View excelBankUpView;
	private View emailBankUpView;
	private View developerView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.data_activity);
		
		setTitle("데이터");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		backupView = findViewById(R.id.dataBackUpView);
		rollbankView = findViewById(R.id.dataRollBankView);
		resetView = findViewById(R.id.dataResetView);
		excelBankUpView = findViewById(R.id.dataExcelBankUpView);
		emailBankUpView = findViewById(R.id.dataEmailBankUpView);
		developerView = findViewById(R.id.dataDeveloperView);
	}

	@Override
	protected void setOnClick()
	{
		backupView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, DataBankUpActivity.class);
				startActivity(intent);
			}
		});
		
		rollbankView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, DataRollBankActivity.class);
				startActivity(intent);
			}
		});
		
		resetView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				MilkUtil.showSelectDialog(superContext, "확인", 
						"가계부를 초기화 하시겠습니까?", 
						new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
						SharedPreferences.Editor editor = pref.edit();
						
						editor.remove(getString(R.string.prefWidgetSelect));
						editor.remove(getString(R.string.prefWidgetYear));
						editor.remove(getString(R.string.prefWidgetMonth));
						editor.remove(getString(R.string.prefWidgetDay));
						editor.remove(getString(R.string.prefStartDate));
						
						editor.commit();
						
						setResetDb();
						setResult(Activity.RESULT_OK);
						finish();
					}
				});
			}
		});
		
		excelBankUpView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, ExcelBankUpActivity.class);
				startActivity(intent);
			}
		});
		
		emailBankUpView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setEmail();
				
				File file = new File(Environment.getExternalStorageDirectory() + "/" 
						+ DataMainActivity.dirNameEmail + "/" + EMAIL_FILE_NAME + ".db");
				
				if (!file.exists())
				{
					MilkUtil.showToast(superContext, "메일파일 생성에 실패 하였습니다. 개발자에게 문의해 주세요.");
					return;
				}
				
				Intent intent = new Intent(Intent.ACTION_SEND);
				
				Uri uri = Uri.fromFile(file);
				
				AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
		        Account[] accounts = am.getAccounts();
		        
		        if (accounts.length > 0)
				{
		        	String [] email = new String[]{accounts[0].name};
		        	intent.putExtra(Intent.EXTRA_EMAIL, email);
				}
		        
				intent.setType("plain/text");
				intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name)); 
				intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.app_name) + " 백업파일");
				
				// 파일 첨부
				intent.putExtra(Intent.EXTRA_STREAM, uri);
				startActivity(intent);
			}
		});
		
		developerView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				String [] email = new String[]{"milkconstant@gmail.com"};
				
				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.putExtra(Intent.EXTRA_EMAIL, email);
				intent.setType("plain/text");
				intent.putExtra(Intent.EXTRA_SUBJECT, "내집 가계부 문의사항");
				startActivity(intent);
			}
		});
	}

	@Override
	protected void setData()
	{
	}
	
	private boolean setResetDb()
	{
		DbSetting setting = null;
		try
		{
			setting = new DbSetting(superContext, superDb);
			
			setting.setBeginTansaction();
			
			setting.setResetDb();
			
			setting.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				setting.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setEmail()
	{
		DbAdapter adapter = DbAdapter.getInstance();
		String path = adapter.getDbPath(superContext);
		adapter.close();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try
		{
			File readfile = new File(path);
			
			if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
			{
				return false;
			}
			
			fis = new FileInputStream(readfile);
			
			File dir = new File(
					Environment.getExternalStorageDirectory() + "/"
							+ DataMainActivity.dirName);
			
			if (!dir.exists())
			{
				dir.mkdir();
			}
			
			File directory = new File(Environment.getExternalStorageDirectory() + "/" 
										+ DataMainActivity.dirNameEmail);
			
			if (!directory.exists())
			{
				directory.mkdir();
			}
			
			String directoryPath = directory.getPath();
			
			File writefile = new File(directoryPath + "/" + EMAIL_FILE_NAME + ".db");
			
			fos = new FileOutputStream(writefile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return false;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
			} catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_DATA);
		startActivity(intent);
	}

}
